<template>
    <LayTable v-bind="t" @change="on_pagination" @sort-change="on_sort" class="table">
        <template v-for="s in Object.keys($slots)" :key="s" v-slot:[s]="sp">
            <slot :name="s" v-bind="sp"></slot>
        </template>
    </LayTable>
</template>

<script setup lang="ts">
import { LayTable } from '@layui/layui-vue';
import { computed } from 'vue';
import type { ColumnSchema, TableEmits, TableSchema } from 'aoe';
import type { TableColumn, TableProps } from '@layui/layui-vue/types/component/table/typing';
import { omit } from 'lodash-es';

const props = defineProps<TableSchema>();
const emits = defineEmits<TableEmits>();

const make_columns = (columns: ColumnSchema[]): Omit<TableColumn, 'rowspan'>[] => {
    const cs = columns.map(
        (column) =>
            ({
                ...omit(column, ['label', 'cell']),
                key: column.name,
                title: column.label ?? column.name,
                customSlot: column.cell ? `$${column.cell}` : undefined,
            }) as Omit<TableColumn, 'rowspan'>,
    );

    if (props.selector) {
        cs.unshift({
            title: '选择',
            type: 'checkbox',
            width: '55px',
            fixed: 'left',
        } as TableColumn);
    }

    return cs;
};

const t = computed<TableProps>(() => ({
    ...(omit(props, ['stripe', 'selector']) || {}),
    dataSource: props.data ?? [],
    columns: props.elements ? make_columns(props.elements) : [],
    even: props.stripe,
    id: props.idKey,
}));

const on_pagination = ({ current }: { current: number }) => emits('pagination', current);
const on_sort = (name: string, direction: 'asc' | 'desc') => emits('sort', name, direction);
</script>

<style scoped></style>
